﻿using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Application.SportBusiness.ISportBusiness;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Global;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Helpers;
using System.Linq;
using SportsPlatform.Application.Dto.Home;
using SportsPlatform.Application.Repository.EmployeeRepository;
using SportsPlatform.Repository.CoreEntity;
using SportsPlatform.Repository.CompetitionRepository;
using NPOI.SS.Formula.Functions;
using SportsPlatform.Model.PermissionManagement;
using System.Globalization;
using Abp.Collections.Extensions;
using System.Collections.Generic;
using Polly.Caching;
using SportsPlatform.Query.PermissionManagement.CompanyInfo;
using SportsPlatform.Application.Query.Home;
using Nest;
using SportsPlatform.Enums;

namespace SportsPlatform.Application.SportBusiness.SportBusiness
{
    /// <summary>
    /// 首页接口实现类
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class HomeService : SportsPlatformAppServiceBase, IHomService
    {
        /// <summary>
        /// 授权仓储接口
        /// </summary>
        private readonly IRepository<AuthorizationInfo, Guid> _authorizationInfoRepository;
        /// <summary>
        /// 客户仓储接口
        /// </summary>
        private readonly IRepository<CompanyInfo, Guid> _companyinfoRepository;
        /// <summary>
        /// 小程序用户仓储接口
        /// </summary>
        private readonly IEmployeeRepository _emloyeeRepository;
        /// <summary>
        /// HttpContext
        /// </summary>
        private readonly IHttpContextAccessor _context;
        /// <summary>
        /// 赛事仓储接口
        /// </summary>
        private readonly ICompetitionRepository _competitionRepository;
        /// <summary>
        /// 赛事项目仓储接口
        /// </summary>
        private readonly IRepository<CompetitionProject, Guid> _projectRepository;

        private readonly IRepository<RegistrationInfo, Guid> _registrationInfoRepository;

        public HomeService(IRepository<CompanyInfo, Guid> companyinfoRepository, IHttpContextAccessor httpContext,
            IEmployeeRepository employeeRepository, ICompetitionRepository competitionRepository,
            IRepository<AuthorizationInfo, Guid> authorizationInfoRepository,
            IRepository<CompetitionProject, Guid> projectRepository,
            IRepository<RegistrationInfo, Guid> registrationInfoRepository) : base(httpContext)
        {
            this._companyinfoRepository = companyinfoRepository;
            this._context = httpContext;
            this._competitionRepository = competitionRepository;
            this._emloyeeRepository = employeeRepository;
            this._authorizationInfoRepository = authorizationInfoRepository;
            this._projectRepository = projectRepository;
            this._registrationInfoRepository = registrationInfoRepository;
        }

        /// <summary>
        /// 获取累计赛事总条数和同比昨日百分比
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<AccumulativeCompetitionDto>> GetAccumulativeCompetitionCount()
        {
            ResultDto<AccumulativeCompetitionDto> resultDto = new ResultDto<AccumulativeCompetitionDto>();
            try
            {
                var sqlKey = "sqls:sql:query_T_B_Competition";
                var strSQL = UldAdminGlobalContext.Configuration.GetSection(sqlKey).Value;
                int totalCount = 0;
                //总条数
                var competitions = await this._competitionRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);
                //查询赛事时间是昨天的数据
                DateTime yesterday = DateTime.Now.AddDays(-1).Date;
                DateTime yesterdayEnd = yesterday.AddDays(1).AddSeconds(-1);
                //昨日
                var yesterdayret = competitions.Where(c => c.CreateTime >= yesterday && c.CreateTime <= yesterdayEnd).Count();
                //今日
                var todayret = competitions.Where(c => c.CreateTime.IsToday()).Count();
                resultDto.Code = 200;
                resultDto.IsSuccess = true;
                resultDto.Data = new AccumulativeCompetitionDto
                {
                    Count = competitions.Count,
                    YesterdayCount = yesterdayret.ToString(),
                    TodayCount = todayret.ToString(),
                    State = yesterdayret == todayret ? 0 : (yesterdayret > todayret ? -1 : 1)
                };
                resultDto.Message = "查询成功";
            }
            catch (Exception ex)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = ex.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取今日新增赛事条数和同比昨日百分比
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<AccumulativeCompetitionDto>> GetAccumulativeCompetitionToDayCount()
        {
            ResultDto<AccumulativeCompetitionDto> resultDto = new ResultDto<AccumulativeCompetitionDto>();
            try
            {
                var sqlKey = "sqls:sql:query_T_B_Competition";
                var strSQL = UldAdminGlobalContext.Configuration.GetSection(sqlKey).Value;
                int totalCount = 0;
                var competitions = await this._competitionRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);
                //今日
                var todayret = competitions.Where(c => c.CreateTime.IsToday()).ToList().Count();
                //查询赛事时间是昨天的数据
                DateTime yesterday = DateTime.Now.AddDays(-1).Date;
                DateTime yesterdayEnd = yesterday.AddDays(1).AddSeconds(-1);
                //昨日
                var yesterdayret = competitions.Where(c => c.CreateTime >= yesterday && c.CreateTime < yesterdayEnd).Count();

                resultDto.Code = 200;
                resultDto.IsSuccess = true;
                resultDto.Data = new AccumulativeCompetitionDto
                {
                    Count = todayret,
                    YesterdayCount = yesterdayret.ToString(),
                    TodayCount = todayret.ToString(),
                    State = yesterdayret == todayret ? 0 : (yesterdayret > todayret ? -1 : 1)
                };
                resultDto.Message = "查询成功";
            }
            catch (Exception ex)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = ex.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取累计注册用户数量
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<RegisterUsersDto>> GetAccumulativeRegistrUsers()
        {
            ResultDto<RegisterUsersDto> resultDto = new ResultDto<RegisterUsersDto>();
            try
            {
                var sqlKey = "sqls:sql:query_T_B_Employee";
                var strSQL = UldAdminGlobalContext.Configuration.GetSection(sqlKey).Value;
                int totalCount = 0;
                var emps = await this._emloyeeRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);
                //查询注册时间是昨天的数据
                DateTime yesterday = DateTime.Now.AddDays(-1).Date;
                DateTime yesterdayEnd = yesterday.AddDays(1).AddSeconds(-1);

                // 使用 yesterday 和 yesterdayEnd 进行数据查询或其他操作
                //昨日
                var yesterdayret = emps.Where(e => e.RegisterTime >= yesterday && e.RegisterTime <= yesterdayEnd).ToList().Count();
                //今日
                var todayret = emps.Where(c => c.RegisterTime.IsToday()).Count();

                resultDto.Code = 200;
                resultDto.IsSuccess = true;
                resultDto.Data = new RegisterUsersDto
                {
                    Count = emps.Count,
                    YesterdayCount = yesterdayret.ToString(),
                    TodayCount = todayret.ToString(),
                    State = yesterdayret == todayret ? 0 : (yesterdayret > todayret ? -1 : 1)
                };
                resultDto.Message = "查询成功";
            }
            catch (Exception ex)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = ex.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取今日累计注册用户
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<RegisterUsersDto>> GetAccumulativeRegistrUsersToDay()
        {
            ResultDto<RegisterUsersDto> resultDto = new ResultDto<RegisterUsersDto>();
            try
            {
                var sqlKey = "sqls:sql:query_T_B_Employee";
                var strSQL = UldAdminGlobalContext.Configuration.GetSection(sqlKey).Value;
                int totalCount = 0;
                var emps = await this._emloyeeRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);
                //查询注册时间是今天的数据
                var todayret = emps.Where(e => e.RegisterTime.IsToday()).Count();

                DateTime yesterday = DateTime.Now.AddDays(-1).Date;
                DateTime yesterdayEnd = yesterday.AddDays(1).AddSeconds(-1);
                //查询昨日数据
                var yesterdayret = emps.Where(e => e.RegisterTime >= yesterday && e.RegisterTime <= yesterdayEnd).Count();
                resultDto.Code = 200;
                resultDto.IsSuccess = true;
                resultDto.Data = new RegisterUsersDto
                {
                    Count = todayret,
                    YesterdayCount = yesterdayret.ToString(),
                    TodayCount = todayret.ToString(),
                    State = yesterdayret == todayret ? 0 : (yesterdayret > todayret ? -1 : 1)
                };
                resultDto.Message = "查询成功";
            }
            catch (Exception ex)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = ex.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取新增用户趋势
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResultDto<Dictionary<string, int>>> GetAddUserTendency(GetAddUserQuery query)
        {
            ResultDto<Dictionary<string, int>> result = new ResultDto<Dictionary<string, int>>();
            try
            {

                var sqlKey = "sqls:sql:query_T_B_Employee";
                var strSQL = UldAdminGlobalContext.Configuration.GetSection(sqlKey).Value;
                int totalCount = 0;
                var emps = await this._emloyeeRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);
                result.Data = new Dictionary<string, int>();
                switch (query.State)
                {
                    case 0:
                        for (int i = 0; i <= 6; i++)
                        {
                            DateTime start=DateTime.Now.AddDays(i-6).Date;
                            DateTime end= start.AddDays(1).AddSeconds(-1);
                            var ret = emps.Where(e => e.RegisterTime >= start && e.RegisterTime <= end).ToList().Count();
                            result.Data.Add(start.DayToWeek(), ret);
                        }
                        break;
                    case 1:
                        //计算月
                        for (int i = 0; i <= 30; i++)
                        {
                            DateTime start = DateTime.Now.AddDays(i - 30).Date;
                            DateTime end = start.AddDays(1).AddSeconds(-1);
                            var ret = emps.Where(e => e.RegisterTime >= start && e.RegisterTime <= end).ToList();
                            result.Data.Add($"{start.Month}.{start.Day}", ret.Count);
                        }
                        break;
                    case 2:
                        //计算年
                        for (int i = 0; i <= 11; i++)
                        {
                            DateTime start = DateTime.Now.AddMonths(i - 11).Date;
                            var ret = emps.Where(e => e.RegisterTime.Month == start.Month).ToList();
                            result.Data.Add($"{start.Year}.{start.Month}", ret.Count);
                        }
                        break;
                }
                result.Code = 200;
                result.IsSuccess = true;
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = ex.ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取待审核的客户信息总数
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<int>> GetPendingInfoCount()
        {
            ResultDto<int> resultDto = new ResultDto<int>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var date = DateTime.Now;

                var authorizationInfos = await _authorizationInfoRepository.GetAllListAsync(r => r.IsDeleted == false && r.States == (int)AuthorizationStateEnum.待审核);

                resultDto.Code = 200;
                resultDto.IsSuccess = true;
                resultDto.Data = authorizationInfos.Count;
                resultDto.Message = "查询成功";
            }
            catch (Exception ex)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = ex.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取今日比赛场次
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<ToDayCompetitionDto>> GetToDayCompetition()
        {
            ResultDto<ToDayCompetitionDto> result = new ResultDto<ToDayCompetitionDto>();
            try
            {
                var projects = await _projectRepository.GetAllListAsync(p => p.IsDeleted == false && p.State != 6 && p.State != 0 && p.State != 1);
                //今日
                var toDay = projects.Where(p => p.GameBeginTime.Date <= DateTime.Now.Date && DateTime.Now.Date <= p.GameEndTime.Date).Count();
                //昨日
                var res = projects.Where(p => p.GameBeginTime.Date <= DateTime.Now.Date && DateTime.Now.Date.AddDays(-1) <= p.GameEndTime.Date).Count();

                result.Code = 200;
                result.IsSuccess = true;
                result.Data = new ToDayCompetitionDto
                {
                    Count = toDay,
                    YesterdayCount = res.ToString(),
                    TodayCount = toDay.ToString(),
                    State = res == toDay ? 0 : (res > toDay ? -1 : 1)
                };
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = ex.ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取今日比赛用户
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<ToDayGameoUserDto>> GetToDayGameoUser()
        {
            ResultDto<ToDayGameoUserDto> result = new ResultDto<ToDayGameoUserDto>();
            try
            {
                //项目
                var projects = await _projectRepository.GetAllListAsync(p => p.IsDeleted == false && p.State != 6 && p.State != 0 && p.State != 1);
                //报名
                var regs = await _registrationInfoRepository.GetAllListAsync(r => r.IsDeleted == false);
                //当日比赛用户        
                var toDay = regs.Where(r => projects.Where(p => p.GameBeginTime.Date <= DateTime.Now.Date && DateTime.Now.Date <= p.GameEndTime.Date && p.Id == r.CompetitionProjectId).Count() > 0
                && r.RegistrationStatus == 2).GroupBy(r => r.CompeteIdNo).Count();

                //昨日比赛用户
                var res = regs.Where(r => projects.Where(p => p.GameBeginTime.Date <= DateTime.Now.Date && DateTime.Now.Date.AddDays(-1) <= p.GameEndTime.Date && p.Id == r.CompetitionProjectId).Count() > 0
                 && r.RegistrationStatus == 2).GroupBy(r => r.CompeteIdNo).Count();

                result.Code = 200;
                result.IsSuccess = true;
                result.Data = new ToDayGameoUserDto
                {
                    Count = toDay,
                    YesterdayCount = res.ToString(),
                    TodayCount = toDay.ToString(),
                    State = res == toDay ? 0 : (res > toDay ? -1 : 1)
                };
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = ex.ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取今日报名用户
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<ToDayRegiisterInfoDto>> GetToDayRegiisterInfo()
        {
            ResultDto<ToDayRegiisterInfoDto> result = new ResultDto<ToDayRegiisterInfoDto>();
            try
            {

                var regs = await _registrationInfoRepository.GetAllListAsync(r => r.IsDeleted == false);
                //今日
                var res = regs.Where(r => r.RegistrationSubmissionTime.IsToday()).Count();
                //查询注册时间是昨天的数据
                DateTime yesterday = DateTime.Now.AddDays(-1).Date;
                DateTime yesterdayEnd = yesterday.AddDays(1).AddSeconds(-1);
                //昨日
                var yesterres = regs.Where(r => r.RegistrationSubmissionTime >= yesterday && r.RegistrationSubmissionTime <= yesterdayEnd).Count();

                result.Code = 200;
                result.IsSuccess = true;
                result.Data = new ToDayRegiisterInfoDto
                {
                    Count = res,
                    YesterdayCount = yesterres.ToString(),
                    TodayCount = res.ToString(),
                    State = yesterres == res ? 0 : (yesterres > res ? -1 : 1)
                };
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = ex.ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取预警信息列表
        /// </summary>
        /// <returns></returns>
        public async Task<PagePagingDto<WarningListDto>> GetWarningList(BasePageQuery query)
        {
            PagePagingDto<WarningListDto> result = new PagePagingDto<WarningListDto>();
            try
            {
                var companyinfos = await _companyinfoRepository.GetAllListAsync(c => c.IsDeleted == false
                && c.States == true);
                if (companyinfos.Count > 0)
                {
                    var pages = companyinfos.OrderBy(c => c.AuthorizeEndTIme).Skip((query.PageIndex - 1) * 3)
                    .Take(3)
                   .ToList();
                    List<WarningListDto> listDtos = new List<WarningListDto>();
                    var date = 0;
                    foreach (var item in pages)
                    {

                        date = item.AuthorizeEndTIme < DateTime.Now ? 0 : Math.Abs(((TimeSpan)(item.AuthorizeEndTIme - DateTime.Now)).Days);
                        if (date <= 31)
                        {
                            var res = new WarningListDto
                            {
                                Describe = item.CompanyName,
                                Day = item.AuthorizeEndTIme < DateTime.Now ? "0天" : Math.Abs(((TimeSpan)(item.AuthorizeEndTIme - DateTime.Now)).Days).ToString() + "天"
                            };
                            if (date == 0)
                            {
                                res.Expired = true;
                                res.Day = "使用已到期";
                            }
                            listDtos.Add(res);
                        }
                    }
                    result.TotalCount = listDtos.Count;
                    result.Data = listDtos;
                    result.Code = 200;
                    result.IsSuccess = true;
                    result.Message = "查询成功";
                }
                else
                {
                    result.Data = new List<WarningListDto>();
                    result.Code = 200;
                    result.IsSuccess = true;
                    result.Message = "未有3个月内，要过期的数据";
                }
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = ex.ToString();
            }
            return result;
        }
    }
}

